import React, {useState, useEffect} from "react";
import {
  Button,
  message,
  PageHeader,
  InputNumber,
  Input,
  Tag,
  Modal,
  Card,
  Alert,
  Table,
  Divider,
  Popconfirm,
  Form,
  Slider,
} from "antd";
import {
  ArrowLeftOutlined,
  PlusOutlined,
  ClockCircleOutlined,
  EditOutlined,
  CheckOutlined,
  ToolOutlined
} from "@ant-design/icons";
import {get} from "server"
import {postJSON, del, putJSON} from "../../shared/server"
import ToolTipsInput from "../../shared/libs/tooltips-input";
import TestDrawer from "./TestDrawer";
import "./index.less"

const {TextArea} = Input;

const priceDescription = {
  A: "套餐固定成本合计/套餐成交价*100",
  B: "套餐变动成本合计/套餐成交价*100",
  C: "套餐其它成本合计/套餐成交价*100",
  D: "成交价/原价(市场价)",
  E: "客单金额与折扣率计算",
  F: "成交价"
}

const priceMap = {
  A: "固定成本率",
  B: "变动成本率",
  C: "其它成本率",
  D: "折扣率",
  E: "业务员提成率",
  F: "成交价"
}

const transfer = (value) => {
  return value.replace(/A/g, priceMap["A"])
    .replace(/B/g, priceMap["B"])
    .replace(/C/g, priceMap["C"])
    .replace(/D/g, priceMap["D"])
    .replace(/E/g, priceMap["E"])
    .replace(/F/g, priceMap["F"])
}

let timerId;

const Formula = (props) => {
  const layout = {
    labelCol: {span: 6},
    wrapperCol: {span: 14},
  };
  const [form] = Form.useForm();
  const [number, setNumber] = useState("");
  const [notice, setNotice] = useState("");
  const [expression, setExpression] = useState("");
  const [expressionTransfer, setExpressionTransfer] = useState("");
  const [numberIsDisabled, setNumberIsDisabled] = useState(false);
  const [expressionIsDisabled, setExpressionIsDisabled] = useState(false);
  const [noticeIsDisabled, setNoticeIsDisabled] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [visible, setVisible] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [recordData, setRecordData] = useState(null);
  const [nameValidate, setnameValidate] = useState({});
  const [drawerVisible, setDrawerVisible] = useState(false);

  const loadEvaluateList = () => {
    get("/management/evaluate").then(result => {
      if (result) {
        setDataSource(result)
      } else {
        message.error("获取评级列表失败")
      }
    })
  }

  const loadConfig = () => {
    get("/management/config/map").then(result => {
      if (result) {
        if (result.expression) {
          setExpression(result.expression.value);
          setExpressionIsDisabled(true);
          setExpressionTransfer(transfer(result.expression.value));
        }
        if (result.notLessThan) {
          setNumber(result.notLessThan.value);
          setNumberIsDisabled(true);
        }
        if (result.announcement) {
          setNotice(result.announcement.value);
          setNoticeIsDisabled(true);
        }
      } else {
        message.error("获取失败");
      }
    })
  }

  useEffect(() => {
    loadConfig();
    loadEvaluateList();
  }, [])


  const handleNumber = () => {
    postJSON("/management/config", {type: "notLessThan", value: number}).then(result => {
      if (result) {
        message.success("设置成功");
        setNumberIsDisabled(true);
        loadConfig();
      } else {
        message.error("设置失败");
      }
    })
  }

  const saveNotice = () => {
    postJSON("/management/config", {type: "announcement", value: notice}).then(result => {
      if (result) {
        message.success("设置成功");
        setNoticeIsDisabled(true);
        loadConfig();
      } else {
        message.error("设置失败");
      }
    })
  }

  const handleExpression = () => {
    postJSON("/management/config", {type: "expression", value: expression}).then(result => {
      if (result) {
        message.success("设置成功");
        loadConfig();
        setExpressionIsDisabled(true);
      } else {
        message.error("设置失败");
      }
    })
  }

  const validate = (value) => {
    get("/management/config/expression/valid", {ex: value}).then(result => {
      if (result) {
        const expressionTransferTmp = transfer(value);
        setExpressionTransfer(expressionTransferTmp);
      } else {
        setExpressionTransfer(null);
      }
    })
  }

  const debounceDelay = (fn, wait = 0, value) => {
    if (timerId) {
      clearTimeout(timerId);
      timerId = null;
    }
    timerId = setTimeout(() => {
      fn(value);
    }, wait);
  }

  const changeExpression = event => {
    let value = event.target.value;
    setExpression(value);
    debounceDelay(validate, 500, value);
  }

  const update = (record) => {
    setVisible(true);
    setIsEdit(true);
    setRecordData(record);
    const {levelName, valueFrom, valueTo, passed = false} = record;
    form.setFieldsValue({
      levelName,
      score: [valueFrom, valueTo],
      passed,
    })
  }

  const deleteItem = (id) => {
    del(`/management/evaluate/${id}`).then(result => {
      if (result) {
        message.success("删除成功");
        loadEvaluateList();
      } else {
        message.error("删除失败")
      }
    })
  }

  const handleChangeNotice = event => {
    const value = event.target.value;
    setNotice(value);
  }

  const columns = [{
    title: "分数",
    dataIndex: "valueFrom",
    key: "valueFrom",
    align: "center",
    render: (text, record) => {
      const {leftValue, rightValue} = record;
      return <span><Tag color={'#00a551'}>包含</Tag>
				<span className={'evaluate-score'}>{leftValue || '--'} ~ {rightValue || '--'}</span>
				<Tag color={'#f50'}>不包含</Tag></span>
    }
  }, {
    title: "结果类型",
    dataIndex: "passed",
    key: "passed",
    align: "center",
    render: (text) => text ? "达标" : "不达标"
  }, {
    title: "评级名称",
    dataIndex: "levelName",
    key: "levelName",
    align: "center",
    render: (v) => {
      return <Tag color={'#fa541c'} className={'large'}>{v}</Tag>
    }
  },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      align: "center",
      render: (text) => text && <Tag className="large"><ClockCircleOutlined/> {text}</Tag>
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      align: "center",
      render: (_, record) =>
        <span>
				<a onClick={() => update(record)}>修改</a>
				<Divider type="vertical"/>
				<Popconfirm
          title="确定要注销此评级吗?"
          placement="rightBottom"
          onConfirm={() => deleteItem(record.id)}
        >
					<a>删除</a>
				</Popconfirm>
			</span>
    }]

  const onFinish = () => {
    form.validateFields().then((values) => {
        const {levelName, score: [valueFrom, valueTo]} = values;
        if (isEdit) {
          putJSON(`/management/evaluate/${recordData.id}`, {
            levelName,
            valueFrom,
            valueTo,
            passed: false
          }).then(result => {
            if (result) {
              message.success("更新成功")
              form.resetFields();
              setVisible(false);
              loadEvaluateList();
            }
          })
        } else {
          postJSON(`/management/evaluate`, {
            levelName,
            valueFrom,
            valueTo,
            passed: false,
          }).then(result => {
            if (result) {
              message.success("添加成功")
              form.resetFields();
              setVisible(false);
              loadEvaluateList();
            }
          })
        }
      }
    ).catch(info => {
      console.log(info, "error info")
    })
  }

  const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
  };

  const handleCancel = () => {
    setVisible(false);
    form.resetFields();
  }

  const addItem = () => {
    setVisible(true)
    form.resetFields();
  }

  const checkLevelName = (value) => {
    return new Promise((resolve, reject) => {
      let postData;
      if (isEdit) {
        postData = {
          id: recordData.id,
          name: value,
        }
      } else {
        postData = {
          name: value,
        }
      }
      get("/management/evaluate/check/name", postData).then(res => {
        if (res) {
          resolve()
        } else {
          reject(`${value}已经存在`)
        }
      }).catch(error => {
        reject(error)
      })
    })
  }

  const handleSeniorTest = () => {
    setDrawerVisible(true);
  }

  const onClose = () => {
    setDrawerVisible(false);
  }

  return (
    <div className={'zr-panel'}>
      <TestDrawer
        visible={drawerVisible}
        onClose={onClose}
      />
      <div className={'zr-panel-header'}>
        <PageHeader backIcon={<ArrowLeftOutlined/>} onBack={() => window.history.back()} title='系统配置' subTitle=''/>
      </div>
      <div style={{padding: "0 20px 20px 20px"}}>
        <Card title="项目限制设置">
          <p>录入项目少于此配置时，不能提交评估</p>
          <InputNumber min={1} style={{width: 100, position: 'relative', top: '1px'}} value={number}
                       onChange={value => setNumber(value)}
                       disabled={numberIsDisabled}
          />
          {
            numberIsDisabled &&
            <Button onClick={() => setNumberIsDisabled(false)} type={'primary'} style={{marginLeft: 5}}><EditOutlined/>编辑</Button>
          }
          {
            !numberIsDisabled &&
            <Button onClick={handleNumber} style={{marginLeft: 5}} type={'primary'}><CheckOutlined/>保存</Button>
          }
          {
            !numberIsDisabled && <Button style={{marginLeft: 5}} onClick={() => {
              setNumberIsDisabled(true);
              loadConfig();
            }}>取消</Button>
          }
        </Card>
        <Card title="项目系统公告" style={{margin: "20px 0"}}>
          <p>设置内容将在小程序端评估窗口显示</p>
          <div className={'announcement-box'}>
            <TextArea
              allowClear
              style={{maxWidth: 800}}
              disabled={noticeIsDisabled}
              autoSize={{minRows: 4, maxRows: 10}}
              value={notice}
              onChange={handleChangeNotice}
            />
            <div className="btns-footer" style={{maxWidth: 800, textAlign: 'right'}}>
              {
                noticeIsDisabled && <Button onClick={() => setNoticeIsDisabled(false)} type={'primary'}
                                            style={{marginLeft: 5}}><EditOutlined/>编辑</Button>
              }
              {
                !noticeIsDisabled &&
                <Button onClick={saveNotice} style={{marginLeft: 5}} type={'primary'}><CheckOutlined/>保存</Button>
              }
              {
                !noticeIsDisabled && <Button style={{marginLeft: 5}} onClick={() => {
                  setNoticeIsDisabled(true);
                  loadConfig();
                }}>取消</Button>
              }
            </div>
          </div>
        </Card>
        <Card title="计算公式设置" style={{margin: "20px 0"}}>
          <h3>参数说明：</h3>
          <p>
            <Tag color="#389e0d" className={'large'}>A</Tag>
            <Tag color="#389e0d" className={'large'}>{priceMap['A']}</Tag>{priceDescription['A']}
          </p>
          <p>
            <Tag color="#08979c" className={'large'}>B</Tag>
            <Tag color="#08979c" className={'large'}>{priceMap['B']}</Tag>{priceDescription['B']}
          </p>
          <p>
            <Tag color="#1890ff" className={'large'}>C</Tag>
            <Tag color="#1890ff" className={'large'}>{priceMap['C']}</Tag>{priceDescription['C']}
          </p>
          <p>
            <Tag color="#d4380d" className={'large'}>D</Tag>
            <Tag color="#d4380d" className={'large'}>{priceMap['D']}</Tag>{priceDescription['D']}
          </p>
          <p>
            <Tag color="#fa8c16" className={'large'}>E</Tag>
            <Tag color="#fa8c16" className={'large'}>{priceMap['E']}</Tag>{priceDescription['E']}
          </p>
          <p>
            <Tag color="#9254de" className={'large'}>F</Tag>
            <Tag color="#9254de" className={'large'}>{priceMap['F']}</Tag>{priceDescription['F']}
          </p>
          {/*<Alert message="" type="info" showIcon/>*/}
          <p>
            公式中具体参数,请使用上述对应字母代替,公式中数字请在数字后添加字母M,例如[0.27M]
          </p>
          <p>
            算术运算符可使用+(加)、-(减)、*(乘)、/(除)、()(圆括号)
          </p>
          <p>
            条件运算符可使用?:(三目运算,条件?成立时公式:不成立时公式)、>(大于)、&lt;(小于)、==(等于)、>=(大于等于),&lt;=(小于等于)
          </p>

          <Input style={{width: 500, marginTop: 10}} placeholder="请输入公式内容" value={expression}
                 onChange={changeExpression}
                 disabled={expressionIsDisabled}
          />
          {
            expressionIsDisabled && <Button onClick={() => setExpressionIsDisabled(false)} type={'primary'}
                                            style={{marginLeft: 5}}><EditOutlined/>编辑</Button>
          }
          {
            !expressionIsDisabled &&
            <Button disabled={!expressionTransfer} onClick={handleExpression} type={'primary'}
                    style={{margin: "0 5px"}}><CheckOutlined/>保存</Button>
          }
          {
            !expressionIsDisabled && <Button style={{marginLeft: 5}} onClick={() => {
              setExpressionIsDisabled(true);
              loadConfig();
            }}>取消</Button>
          }
          <Button onClick={handleSeniorTest} type={'primary'} style={{marginLeft: 5}}><ToolOutlined/>配置测试</Button>
          {
            expressionTransfer ?
              <p className={'expression-trans'}>
                {expressionTransfer}
              </p>
              : <p className="notMatch">
                公式不合法
              </p>
          }
        </Card>
        <Card title="评分等级设置" className={'table-card'} extra={
          <Button type="primary" onClick={addItem}><PlusOutlined/>新增</Button>
        }>
          <Table
            size={'small'}
            pagination={false}
            columns={columns}
            rowKey={record => record.id}
            dataSource={dataSource}
          />
        </Card>
        <Modal
          title={isEdit ? "编辑" : "新增"}
          visible={visible}
          onOk={onFinish}
          onCancel={handleCancel}
        >
          <Form
            {...layout}
            style={{paddingTop: 20, width: 500, margin: "0 auto"}}
            form={form}
            name="basic"
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            initialValues={{
              score: [-30, -10],
              passed: false,
            }}
          >
            <Form.Item
              label="评级名称"
              name="levelName"
              hasFeedback
              {...nameValidate}
              validateFirst={true}
              rules={[
                {required: true, message: "评级名称必须填写"},
                {
                  validator: (rule, value, callback) => checkLevelName(value)
                }
              ]}
            >
              <ToolTipsInput
                title="评级名称只能4-20位[数字/字母/@.]"
                id="_levelName"
                placeholder="请输入评级名称"
              />
            </Form.Item>
            {/* <Form.Item name="passed" label="是否达标"
							validateFirst={true}
              rules={[
                { required: true, message: '是否达标必须填写' },
              ]}
            >
              <Radio.Group>
                <Radio value={false} key="1">不达标</Radio>
                <Radio value={true} key="2">达标</Radio>
              </Radio.Group>
            </Form.Item> */}
            <Form.Item
              label="分数"
              name="score"
              validateFirst={true}
              rules={[
                {required: true, message: "分数必须填写"},
              ]}
            >
              <Slider
                marks={{
                  "-100": -100,
                  "-50": -50,
                  0: 0
                }}
                reverse
                range
                min={-100}
                max={0}
                step={1}
              />
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </div>
  )
}
export default Formula